package com.jason.ladder.webapp.controller;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.jason.ladder.Constants;
import com.jason.ladder.entityManager.EMF;
import com.jason.ladder.model.User;

@Controller
@RequestMapping("/content/login")

public class LoginController {
	private PasswordEncoder passwordEncoder;
    private static Logger logger = Logger.getLogger( LoginController.class );

    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
    
    @SuppressWarnings("unchecked")
    @RequestMapping(method=RequestMethod.GET)
    public void doGet(){
    	
    }
   
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView login( User user, HttpServletRequest request ) throws IOException {
            
            ModelAndView mav = new ModelAndView();
            
            EntityManager em = EMF.get().createEntityManager();
            List<User> users;
            try {       
            	
            	String queryStr = "select p from User p where p.email = :email";
            	
            	//queryStr.replaceFirst("?", user.getEmail()).replaceFirst("?", user.getPassword());
                javax.persistence.Query query = em.createQuery(queryStr);
                query.setParameter("email", user.getEmail());
                //query.setParameter("password", user.getPassword());
               
                users = (List<User>)query.getResultList();
                if(users.size()>0){
                	Iterator<User> it = users.iterator();
					while(it.hasNext()){
						User thisUser = it.next();
						if(passwordEncoder.isPasswordValid(thisUser.getPassword(), user.getPassword(), null)){
							request.getSession(true).setAttribute( Constants.SESSION_USER , thisUser);
		                	mav.setViewName("redirect:/content/ladder");
						}else{
							mav.setViewName("login");
						}
					}
                	
                }else{
                	mav.setViewName("login");
                }
                	
            } finally {
                em.close();
            }
            return mav;
    }
    
   
}
